<?php
namespace app\shop\model;
use app\BaseModel;
use app\shop\model\IndexShopSpePrice;
use think\facade\Db;



class IndexShopCollageList extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_shop_collage_list';

    /**
     * @param $value
     * @param $data
     * @return mixed
     * 状态
     */
//    public function getcollageStatusAttr($value){
//        if(in_array($value,[1,2,3,4])){
//            $status = [1=>'拼团中',2=>'拼团完成',3=>'拼团完成',4=>'拼团超时'];
//            return $status[$value];
//        }
//    }


        /**
     * @param $dis
     * @param int $page
     * @return mixed
     * 获取拼团列表
     */
    public function collageList($dis,$page = 10){
        $data = self::where($dis)->paginate($page)->toArray();
        return $data;
    }

    /**
     * @param $dis
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取拼团信息
     */
    public function collageInfo($dis){
       $data = $this->where($dis)->find();
       return !empty($data)?$data->toArray():$data;

    }

    /**
     * @param $dis
     * @param $data
     * @return IndexShopCollageList
     * 编辑拼团信息
     */

    public function collageUpdate($dis,$data){
        $data['update_time'] = time();
        $res = $this->where($dis)->update($data);
        return $res;

    }
    /**
     * @param $dis
     * @param $data
     * @return IndexShopCollageList
     * 添加拼团信息
     */

    public function collageAdd($data){
        $data['update_time'] = time();
        $data['create_time'] = time();
        $res = $this->insert($data);
        $res = $this->getLastInsID();
        return $res;

    }

    /**
     * @param $dis
     * @return bool
     * @throws \Exception
     * 删除拼团信息
     */

    public function collageDel($dis){
        $res = $this->where($dis)->delete();
        return $res;
    }


    /**
     * @param $dis
     * 获取用户拼团信息
     */
    public function userCollageList($dis,$uid,$collage_overtime,$page=10){

        $data = $this
            ->alias('a')
            ->leftJoin('longbing_card_user b' ,'a.user_id = b.id')
            ->leftJoin('longbing_card_goods c' ,'a.goods_id = c.id')
            ->leftJoin('longbing_card_shop_collage d' ,'a.collage_id = d.id')
            ->where($dis)
            ->where('a.collage_status','=',1)
            ->where('a.left_number','>',0)
            ->field(['a.id,a.collage_status,a.user_id, a.goods_id, a.left_number, a.create_time, b.nickName, b.avatarUrl,c.freight, c.name, c.cover,c.collage_count, c.unit, d.spe_price_id, d.number, d.price, d.people'])
            ->order('a.id desc')
            ->paginate($page)
            ->toArray();
        if(!empty($data['data'])){
            foreach ($data['data'] as &$value){

                $spe_model = new IndexShopSpePrice();

//                $spe       = $spe_model->SpePriceFind(['goods_id'=>$value['goods_id'],'status'=>1]);
                $spe       = $spe_model->SpePriceFind(['id'=>$value['spe_price_id'],'status'=>1]);

                $value['title']     = !empty($spe['spe_name_text'])?$spe['spe_name_text']:'';

                $value['countdown'] = $collage_overtime - (time() - $value['create_time']);

                $value['left_time'] = lbGetDatess($value['countdown']);

                $user_collage       = Db::name('longbing_card_shop_user_collage')->where(['collage_id'=>$value['id'],'user_id'=>$uid])->find();

                $value['can_collage']=1;

                if($uid == $value['user_id']||$user_collage){

                    $value['can_collage'] = 0;

                }

            }

        }
        $data['data']  = transImages($data['data'],['cover'],',');

        return $data;
    }

    /**
     * @param $dis
     * 获取用户拼团信息
     */
    public function userCollageInfo($dis,$uid,$collage_overtime){

        $data = $this
            ->alias('a')
            ->leftJoin('longbing_card_user b' ,'a.user_id = b.id')
            ->leftJoin('longbing_card_goods c' ,'a.goods_id = c.id')
            ->leftJoin('longbing_card_shop_collage d' ,'a.collage_id = d.id')
            ->where($dis)
            ->field(['a.id,a.collage_status,a.user_id, a.goods_id, a.left_number, a.create_time, b.nickName, b.avatarUrl,c.freight, c.name, c.cover,c.collage_count, c.is_self,c.is_send,c.unit, d.spe_price_id, d.number, d.price, d.people'])
            ->order('a.id desc')
            ->find();
        if(!empty($data)){
            $data      = $data->toArray();
            $spe_model = new IndexShopSpePrice();
//            $spe       = $spe_model->SpePriceFind(['goods_id'=>$data['goods_id'],'status'=>1]);

            $spe       = $spe_model->SpePriceFind(['id'=>$data['spe_price_id'],'status'=>1]);
            $data['title']      = !empty($spe['spe_name_text'])?$spe['spe_name_text']:'';
            $data['countdown']  = $collage_overtime - (time() - $data['create_time']);
            $data['left_time']  = lbGetDatess($data['countdown']);
            $user_collage       = Db::name('longbing_card_shop_user_collage')->where(['collage_id'=>$data['id'],'user_id'=>$uid])->find();
            $data['can_collage']= !empty($user_collage)&&in_array($user_collage['collage_status'],[1,2,3])?0:1;
        }
        $data  = transImages($data,['cover'],',');
        return $data;
    }





    /**
     * @param $collage_id
     * @param $goods_info
     * @param $number
     * @param $is_start
     * @param $user_id
     * @功能说明:拼团
     * @author chenniang
     * @DataTime: 2021-02-01 16:12
     */
    public function DoAtv($input){

//        if(!empty($input['is_integral'])){
//
//            return ['code'=>500,'msg'=>'积分活动商品不能拼团'];
//
//        }
//
//        if(!empty($input['bargain_id'])){
//
//            return ['code'=>500,'msg'=>'拼团活动商品不能砍价'];
//
//        }

        if(!empty($input['collage_id'])&&empty($input['bargain_id'])&&empty($input['is_integral'])){

            if(!empty($input['collage_satrt'])&&$input['collage_satrt']==1){

                $data = $this->startCollage($input['collage_id'],$input['goods_info'],$input['number'],$input['user_id']);

            }else{

                $data = $this->joinCollage($input['collage_id'],$input['number'],$input['user_id']);
            }

            if(!empty($data['code'])){

                return $data;
            }

            $pay_price  = sprintf( '%.2f', $data['data'][ 'price' ]);

            $arr['price']         = $pay_price;

            $arr['collage_type']  = 1;

            $arr['collage_id']    = $data['id'];

            return $arr;
        }

        return [];

    }


    /**
     * @param $collage_id
     * @param $number
     * @功能说明:加入拼团
     * @author chenniang
     * @DataTime: 2021-02-01 16:02
     */
    public function joinCollage($collage_id,$number,$user_id){

        $collage_model = new IndexShopCollage();

        $user_collage_model = new IndexUserCollage();

        $collage = $this->collageInfo(['id'=> $collage_id]);

        if(empty($collage)){

            return ['code'=>500,'msg'=>'拼团未找到'];

        }

        $collage2 = $collage_model->collageInfo([ 'id' => $collage[ 'collage_id' ]]);

        if ( !$collage2 || $number < $collage2[ 'number' ] ) {

            return ['code'=>500,'msg'=>'拼团信息错误'];

        }

        $left_number = $collage['left_number'];

        if($left_number<=0){

            return ['code'=>500,'msg'=>'拼团人数已满'];

        }

        $res = $this->checkCollageLimit($collage2,$user_id);

        if(!empty($res['code'])){

            return $res;
        }

        $this->collageUpdate([ 'id' => $collage_id ],['left_number'=>Db::raw('left_number-1')] );

        $insert_data = [

            'user_id'    => $user_id,

            'collage_id' => $collage_id,

            'uniacid'    => $collage['uniacid']
        ];

        $user_collage_model->collageAdd($insert_data);

        $re_data['data'] = $collage2;

        $re_data['id']   = $collage_id;

        return $re_data;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-02-02 10:44
     * @功能说明:拼团信息
     */
    public function payCollageInfo($collage_id){

        $collage_model = new IndexShopCollage();

        $collage = $collage_model->collageInfo([ 'id' => $collage_id]);

        return $collage;

    }


    /**
     * @param $collage_id
     * @param $goods_info
     * @param $number
     * @功能说明:发起拼团
     * @author chenniang
     * @DataTime: 2021-02-01 16:09
     */
    public function startCollage($collage_id,$goods_info,$number,$user_id){

        $collage_model = new IndexShopCollage();

        $user_collage_model = new IndexUserCollage();

        $collage = $collage_model->collageInfo(['goods_id' => $goods_info['id'], 'id'=> $collage_id]);

        if(empty($collage)){

            return ['code'=>500,'msg'=>'拼团未找到'];

        }
        if ($number < $collage[ 'number' ]) {

            return ['code'=>500,'msg'=>'拼团信息错误'];

        }

        $res = $this->checkCollageLimit($collage,$user_id);

        if(!empty($res['code'])){

            return $res;
        }

        $insertCollageListData = array(
            'user_id'     => $user_id,
            'goods_id'    => $goods_info['id'],
            'collage_id'  => $collage_id,
            'name'        => $goods_info[ 'name' ],
            'cover'       => $goods_info[ 'cover' ],
            'number'      => $collage[ 'people' ],
            'left_number' => $collage[ 'people' ] - 1,
            'price'       => $collage[ 'price' ],
            'uniacid'     => $collage['uniacid'],
        );
        $collage_list_id = $this->collageAdd($insertCollageListData);

        if ( !$collage_list_id ) {

            return ['code'=>500,'msg'=>'拼团失败'];

        }
        $insert_data = [

            'user_id'     => $user_id,

            'collage_id'  => $collage_list_id,

            'uniacid'     => $collage['uniacid']
        ];
        $user_collage_model->collageAdd($insert_data);

        $re_data['data'] = $collage;

        $re_data['id']   = $collage_list_id;

        return $re_data;
    }


    /**
     * @param $collage
     * @功能说明:检查拼团
     * @author chenniang
     * @DataTime: 2021-02-01 16:05
     */
    public function checkCollageLimit($collage,$user_id){

        if ($collage['limit']) {

            $user_collage_model = new IndexUserCollage();

            $collage_dis = [

                'collage_id' => $collage['id']
            ];
            //获取这个拼团活动所有的拼团id
            $collage_id = $this->where($collage_dis)->where('collage_status','<>',4)->column('id');

            if (!empty($collage_id)){

                $where[] = ['collage_id','in',$collage_id];
                //出去拼团失败的
                $where[] = ['collage_status','<>',4];

                $where[] = ['user_id','=',$user_id];
                //查找自己是有插件过拼团
                $check = $user_collage_model->where($where)->find();

                if(!empty($check)){

                    return ['code'=>500,'msg'=>'已经参加过此拼团, 不能重复参加'];

                }

            }

        }
        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-21 14:59
     * @功能说明:拼团信息
     *
     */
    public function DoAtvPrice($input,$spe,$goods){

        $collage_list_model = new IndexShopCollageList();

        if(!empty($input['collage_satrt'])&&$input['collage_satrt']==1){

            $collage_data = $this->payCollageInfo($input['collage_id']);

        }else{

            $collage_data = $collage_list_model->collageInfo(['id'=>$input['collage_id']]);

        }

        if(empty($collage_data)){

            return ['code'=>500,'msg'=>'拼团未找到'];
        }

        $spe['price'] = $collage_data['price'];

        $data['spe']   = $spe;

        $data['goods'] = $goods;

        return $data;

    }





}